package com.magicode.portal.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.magicode.cms.entiy.base.BuyHistory;
import com.magicode.cms.entiy.base.Channel;
import com.magicode.cms.entiy.base.ChannelBuyHistory;
import com.magicode.cms.entiy.base.Dictionary;
import com.magicode.cms.entiy.base.News;
import com.magicode.cms.entiy.base.NewsBuyHistory;
import com.magicode.cms.entiy.base.OfflineEvents;
import com.magicode.cms.entiy.base.OfflineEventsUser;
import com.magicode.cms.entiy.base.OfflineEventsUserBuyHistory;
import com.magicode.cms.entiy.base.PayHistory;
import com.magicode.cms.entiy.base.Picture;
import com.magicode.cms.entiy.base.User;
import com.magicode.cms.entiy.base.UserCoin;
import com.magicode.cms.entiy.base.UserCoinHistory;
import com.magicode.cms.entiy.base.VipBuyHistory;
import com.magicode.cms.entiy.base.VipBuyRule;
import com.magicode.cms.service.IDictionary;
import com.magicode.cms.service.IUserCoinService;
import com.magicode.cms.service.IVideoService;
import com.magicode.common.exception.BusinessException;
import com.magicode.common.util.DateUtil;
import com.magicode.portal.dao.IMoneyDao;
import com.magicode.portal.service.IMoneyService;

@Service("moneyService")
public class MoneyServiceImpl implements IMoneyService{
	//收费VIP编码
	private String chargeVipCode = "chargeVip";
	//加减用户订单豆币
	@Override
	@Transactional
	public void refreshTransaction(String  userid2,Map<String,String> objprams)throws Exception{
		if(!objprams.containsKey("buyhistoryid")){
			throw new Exception("refreshTransaction but not find buyhistoryid by objprams ["+objprams.toString()+"]");
		}
		String buyhistoryid = objprams.get("buyhistoryid");
		BuyHistory buyhistory = moneydao.getBuyHistoryByid(buyhistoryid);
		//已购买成功返回
		String code = buyhistory.getStatus().getCode();
		if("Success".equals(code)){
			return;
		}
		
		UserCoin  usercoin = serviceUserCoin.getUserCoin(buyhistory.getUser().getId());
		if(usercoin.getCoinCount()>=buyhistory.getResumeCoin()&&0!=buyhistory.getResumeCoin()){
			int ucion = usercoin.getCoinCount() - buyhistory.getResumeCoin();
			//刷新用户豆币余额
			usercoin.setCoinCount(ucion);
			//记录豆币历史
			UserCoinHistory usercoin_history = new UserCoinHistory();
			usercoin_history.setUserCoin(usercoin);
			usercoin_history.setCreateTime(new Date());
			usercoin_history.setCoinCount(-buyhistory.getResumeCoin());
			usercoin_history.setCoinFinalCount(ucion);
			usercoin_history.setUsserEvent("豆币消费");
			//购买历史状态 成功
			Dictionary dic = daoDictionary.getDictionaryByDictionaryTypeCode("BuyStatus","Success");
			buyhistory.setStatus(dic);
			moneydao.refreshTransaction(buyhistory, usercoin, usercoin_history);
		}
		
	}
	@Override
	public String addPayHistory(User user, Map<String, String> objprams) {
		try {
			PayHistory pay_hostory = new PayHistory();
			int resumeCoin = Integer.valueOf(objprams.get("resumeCoin"));
			String paytype = objprams.get("payType");
			if(null!=paytype && !"".equals(paytype)){
				//支付类别 (平台类别 微信，支付宝等 )
				Dictionary type = daoDictionary.getDictionaryByDictionaryTypeCode("PayType", paytype);
				pay_hostory.setPayType(type);
			}
			pay_hostory.setResumeCoin(resumeCoin);
			//设置购买 待付款 状态
			Dictionary dic = daoDictionary.getDictionaryByDictionaryTypeCode("PayStatus", "Waiting");
			if(dic == null){
				throw new BusinessException("无法找到支付状态");
			}
			pay_hostory.setStatus(dic);
			pay_hostory.setUser(user);
			moneydao.addPayHistory(pay_hostory);
			return pay_hostory.getId();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		
	}

	@Transactional
	public String addBuyHistory(User user,Map<String,Object> objprams,int type){
		try {
			BuyHistory buy_hostory = null;
			
			switch (type) {
			case 0:
				//购买视频或文章
				buy_hostory =new NewsBuyHistory();
				News news = (News)daoDictionary.getObject(News.class.getName(), objprams.get("newsid").toString());
				PropertyUtils.setProperty(buy_hostory, "news", news);
				PropertyUtils.setProperty(buy_hostory, "type", news.getType());
				break;
			case 1:
				//购买会员
				buy_hostory =new VipBuyHistory();
				Dictionary vipType = new Dictionary();
				vipType.setId((String)objprams.get("vipTypeId"));
				VipBuyRule vbr = new VipBuyRule();
				vbr.setId((String)objprams.get("vipBuyRuleId"));
				PropertyUtils.setProperty(buy_hostory, "vipBuyRule", vbr);
				PropertyUtils.setProperty(buy_hostory, "vipuser", user);
				break;
			case 2:
				//购买频道
				buy_hostory =new ChannelBuyHistory();
				Channel channel = (Channel)daoDictionary.getObject(Channel.class.getName(), objprams.get("channelId").toString());
				PropertyUtils.setProperty(buy_hostory, "channel", channel);
				break;
			case 3:
				//购买频道
				buy_hostory =new OfflineEventsUserBuyHistory();
				OfflineEventsUser offlineEventsUser = (OfflineEventsUser)daoDictionary.getObject(OfflineEventsUser.class.getName(), objprams.get("offlineeventsuserid").toString());
				PropertyUtils.setProperty(buy_hostory, "offlineEventsUser", offlineEventsUser);
				break;
			default:
				break;
			}
			PropertyUtils.setProperty(buy_hostory, "validEndTime", objprams.get("validEndTime"));
			PropertyUtils.setProperty(buy_hostory, "validBeginTime", new Date());
			buy_hostory.setResumeCoin(Integer.valueOf(objprams.get("resumeCoin").toString()));
			buy_hostory.setUser(user);
			Dictionary dic = daoDictionary.getDictionaryByDictionaryTypeCode("BuyStatus", "Waiting");
			buy_hostory.setStatus(dic);
			
			moneydao.addBuyHistory(buy_hostory);
			return buy_hostory.getId();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
		
	}
	/**
	 * 是否存在未支付的订单
	 * @return
	 * @throws Exception 
	 */
	@Override
	public boolean isExistOrderOutOfPay(User user) throws Exception{
		if(null != user){
			//待购买的订单查询
			Dictionary dic = daoDictionary.getDictionaryByDictionaryTypeCode("BuyStatus", "Waiting");//待购买状态
			if(null != dic){
				String hql="from "+BuyHistory.class.getName()+" t left outer join fetch t.user left outer join fetch t.status where t.user.id=:userId and t.status.id=:dicId ";
				Map<String,String> map = new HashMap<String, String>();
				map.put("userId",user.getId().trim());
				map.put("dicId",dic.getId());
				List<BuyHistory> buyHis=this.getMoneydao().getICommonDaoService().queryList(hql,map);
				if(buyHis.size()>0){
					return true;
				}
			}
			//正在支付的订单查询
			dic = daoDictionary.getDictionaryByDictionaryTypeCode("BuyStatus", "Doing");//正在购买状态
			if(null != dic){
				String hql="from "+BuyHistory.class.getName()+" t left outer join fetch t.user left outer join fetch t.status where t.user.id=:userId and t.status.id=:dicId ";
				Map<String,String> map = new HashMap<String, String>();
				map.put("userId",user.getId().trim());
				map.put("dicId",dic.getId());
				List<BuyHistory> buyHis=this.getMoneydao().getICommonDaoService().queryList(hql,map);
				if(null != buyHis && buyHis.size() > 0){
					return true;
				}
			}
		}
		return false;
	}
	@Override
	public void cancelOrder(String id) throws Exception {
		Dictionary dic = daoDictionary.getDictionaryByDictionaryTypeCode("BuyStatus", "Cancel");//撤销购买
		if(null != id){
			String hql = "from " + BuyHistory.class.getName() + " t left outer join fetch t.payHistory where t.id=:id ";
			Map<String,String> map = new HashMap<String, String>();
			map.put("id",id);
			List<BuyHistory> buyHisList = this.getMoneydao().getICommonDaoService().queryList(hql,map);
			if(null != dic && null != buyHisList && buyHisList.size() > 0){
				BuyHistory buyHis = buyHisList.get(0);
				buyHis.setStatus(dic);
				moneydao.getICommonDaoService().update(buyHis);
				PayHistory payHistory = buyHis.getPayHistory();
				if(null != payHistory){
					dic = daoDictionary.getDictionaryByDictionaryTypeCode("PayStatus", "Cancel");//撤销支付
					if(null != dic){
						payHistory.setStatus(dic);
						moneydao.editObject(payHistory);
					}
				}
			}
		}
	}
	@Override
	public void cancelPay(String id) throws Exception{
		Dictionary dic = daoDictionary.getDictionaryByDictionaryTypeCode("PayStatus", "Cancel");//撤销支付
		if(null != id){
			String hql = "from " + PayHistory.class.getName() + " t  where t.id=:id ";
			Map<String,String> map = new HashMap<String, String>();
			map.put("id",id);
			List<PayHistory> list = this.getMoneydao().getICommonDaoService().queryList(hql,map);
			if(null != list && list.size() > 0){
				PayHistory payHistory = list.get(0);
				if(null != dic){
					payHistory.setStatus(dic);
					moneydao.editObject(payHistory);
				}
			}
		}
	}
	
	@Override
	public void saveQrCodePic(Picture picture, PayHistory payHistory) throws Exception {
		if(null != picture && null != payHistory){
			if(null == picture.getId()){
				this.moneydao.getICommonDaoService().save(picture);
			}
			payHistory.setQrCodePic(picture);
			moneydao.editObject(payHistory);
		}
	}
	@Override
	public boolean isSuccessBuy(String buyhistoryid) throws Exception {
		Dictionary dictionary1 = daoDictionary.getDictionaryByDictionaryTypeCode("BuyStatus", "Success");
		Dictionary dictionary = daoDictionary.getDictionaryByDictionaryTypeCode("PayStatus", "Success");
		String hql = " select t from " + BuyHistory.class.getName() + " t ," + PayHistory.class.getName() + " p where t.payHistory.id=p.id and p.status.id=:paydicId and t.status.id=:buydicId and t.id=:id ";
		Map<String,String> map = new HashMap<String, String>();
		map.put("id", buyhistoryid);
		map.put("paydicId", dictionary.getId());
		map.put("buydicId", dictionary1.getId());
		List<BuyHistory> list =  moneydao.getICommonDaoService().getListBySQLMap(hql, map);
		if(null != list && list.size() > 0){
			return true;
		}
		return false;
	}
	@Override
	public boolean isSuccessPay(String payBuyhistoryId) throws Exception{
		Dictionary dictionary = daoDictionary.getDictionaryByDictionaryTypeCode("PayStatus", "Success");
		String hql = " from " + PayHistory.class.getName() + " t  where t.id=:id and t.status.id=:dicId";
		Map<String,String> map = new HashMap<String, String>();
		map.put("id", payBuyhistoryId);
		map.put("dicId", dictionary.getId());
		List<PayHistory> list = moneydao.getICommonDaoService().getListBySQLMap(hql, map);
		if(null != list && list.size() > 0){
			return true;
		}
		return false;
	}
	
	@Override
	public BuyHistory getBuyHistoryByPayId(String payhistoryid, String user_id) {
		String hql = " from " + BuyHistory.class.getName() + " t left outer join fetch t.status where t.user.id=:user_id and t.payHistory.id=:payid";
		Map map = new HashMap();
		map.put("payid", payhistoryid);
		map.put("user_id", user_id);
		List<BuyHistory> list = moneydao.getICommonDaoService().getListBySQLMap(hql, map);
		if(null != list && list.size() > 0){
			return list.get(0);
		}
		return null;
	}
	@Override
	public BuyHistory getBuyHistoryById(String buyhistoryid) {
		String hql = " from " + BuyHistory.class.getName() + " t left outer join fetch t.status left outer join fetch t.payHistory where t.id=:id";
		Map<String,String> map = new HashMap<String, String>();
		map.put("id", buyhistoryid);
		List<BuyHistory> list = moneydao.getICommonDaoService().getListBySQLMap(hql, map);
		if(null != list && list.size() > 0){
			return list.get(0);
		}
		return null;
	}
	@Override
	@Transactional
	//购买豆币成功后刷新用户豆币记录
	public void returnPayHistory(String userid, Map<String, String> objprams) throws Exception{

		PayHistory pay_hostory = null;
		if(!objprams.containsKey("payhistoryid")){
			throw new Exception(" returnPayHistory error but not find payhistoryid----- ");
		}
		//支付状态
		String paystatus = objprams.get("paystatus");
		String payhistoryid = objprams.get("payhistoryid");
		pay_hostory = moneydao.getPayHistoryByid(payhistoryid);
		//已购买成功返回
		String code = pay_hostory.getStatus().getCode();
		if("Success".equals(code)){
			return;
		}
		Dictionary paydic = daoDictionary.getDictionaryByDictionaryTypeCode("PayStatus",paystatus);
		pay_hostory.setStatus(paydic);
		//购买豆币数量
		int resumeCoin = pay_hostory.getResumeCoin();
		//修改用户豆币余额
		UserCoin  usercoin = serviceUserCoin.getUserCoin(userid);
		int  resultcoin =  usercoin.getCoinCount()+resumeCoin;
		usercoin.setCoinCount(resultcoin);
		UserCoinHistory usercoin_history = null;
		if(0!=resumeCoin){
			usercoin_history = new UserCoinHistory();
			usercoin_history.setUserCoin(usercoin);
			usercoin_history.setCreateTime(new Date());
			usercoin_history.setCoinCount(resumeCoin);
			usercoin_history.setCoinFinalCount(usercoin.getCoinCount()+resumeCoin);
			usercoin_history.setUsserEvent("豆币充值");
		}
		moneydao.returnPayHistory(pay_hostory,usercoin, usercoin_history);
	}
	@Autowired
	@Qualifier("servicevideo")
	private IVideoService videoService;
	@Override
	public List<Map<String,Object>> getUserCoinHistorys(Map<String, String> prams) {
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		try {
			List<PayHistory> his = moneydao.getUserCoinHistorys(prams);
			for(PayHistory his_ : his){
				if(null != his_.getPayType() && "WeichatPay".equals(his_.getPayType().getCode()) && null != his_.getStatus() && "Waiting".equals(his_.getStatus().getCode())){
					continue;
				}
				Map<String,Object>  prams_ = new HashMap<String,Object>();
				prams_.put("id", his_.getId());
				prams_.put("ordernumber", his_.getId().substring(his_.getId().length()-5,his_.getId().length()));
				prams_.put("timestr", DateUtil.getInstance().dateToString(his_.getBeginTime()));
				//充值购买数量
				prams_.put("resumecoin",his_.getResumeCoin() );
				prams_.put("coinfinalcount", his_.getResumeCoin());
				//his_.getType().getTitle();
				prams_.put("status_type",21);
//				System.out.println(his_.getStatus().getCode());
				if(null!=his_.getStatus() && his_.getStatus().getCode().equals("Waiting")){
					prams_.put("status_type",30);
				}else{
					prams_.put("status_type",31);
				}
				if(null != his_.getStatus()){
					prams_.put("status",his_.getStatus().getTitle());
					prams_.put("statuscode",his_.getStatus().getCode());
				}
				prams_.put("invoicestatus", his_.getInvoicestatus());
				prams_.put("usserevent","M币充值");
				result.add(prams_);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return result;
	}
	@Override
	public List<Map<String, Object>> getUserBuyHistory(Map<String, String> prams) {
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		try {
			// TODO Auto-generated method stub
			List<BuyHistory>  bhistory= moneydao.getUserBuyHistorys(prams);
			for(BuyHistory his_ : bhistory){
				Map<String,Object>  prams_ = new HashMap<String,Object>();
				prams_.put("id", his_.getId());
				prams_.put("ordernumber", his_.getId().substring(his_.getId().length()-5,his_.getId().length()));
				if(null != his_.getBeginTime()){
					prams_.put("timestr", DateUtil.instance.dateToString(his_.getBeginTime()));
				}
				//充值购买数量
				prams_.put("resumecoin", his_.getResumeCoin());
				//余额
				//prams_.put("coinfinalcount", his_.getCoinFinalCount());
				//his_.getType().getTitle();
				prams_.put("invoicestatus", his_.getInvoicestatus());
				Dictionary status = his_.getStatus();
				prams_.put("status",null==status?"": status.getTitle());
				//消费内容
				String usserevent="";
				if(his_ instanceof ChannelBuyHistory){
					ChannelBuyHistory channeHistory = moneydao.getChannelBuyHistoryById(his_.getId());
					if(null!=channeHistory){
						prams_.put("usserevent_id",channeHistory.getChannel().getId());
						prams_.put("usserevent_type",channeHistory.getChannel().getType());
						usserevent = channeHistory.getChannel().getTitle();
						if(null!=status && status.getCode().equals("Waiting")){
							prams_.put("status_type",10);
						}else{
							prams_.put("status_type",11);
						}
					}
				}else if(his_ instanceof OfflineEventsUserBuyHistory){
					OfflineEventsUserBuyHistory offBuyHistory = moneydao.getOfflineBuyHis(his_.getId());
					if(null!=offBuyHistory){
						prams_.put("usserevent_id",offBuyHistory.getOfflineEventsUser().getId());
						String hql = " from " + OfflineEventsUser.class.getName() + " t left outer join fetch t.offlineEvents where t.id=:id";
						Map map = new HashMap();
						map.put("id", offBuyHistory.getOfflineEventsUser().getId());
						OfflineEventsUser offlineEventsUser = (OfflineEventsUser) moneydao.getICommonDaoService().getByHQLMap(hql, map);
						usserevent = offlineEventsUser.getOfflineEvents().getTitle();
						if(null!=status && status.getCode().equals("Waiting")){
							prams_.put("status_type",40);
						}else{
							prams_.put("status_type",41);
						}
					}
				}
				else if(his_ instanceof VipBuyHistory){
					prams_.put("usserevent_type",99);
					VipBuyHistory vip = (VipBuyHistory)his_;
					if(null!=vip.getValidEndTime()){
						String datestr = DateUtil.getInstance().dateToStringDate(vip.getValidEndTime());
						if(vip.getVipBuyRule() != null){
//							String ruleId = vip.getVipBuyRule().getId();
							Dictionary vipType = null;
							vipType = getVipTypeByBuyHistoryId(vip.getId());
							if(vipType != null){
								usserevent=vipType.getTitle()+"至("+datestr+")";
							}
							else{
								usserevent="购买会员至("+datestr+")";
							}
						}
						else{
							usserevent="购买会员至("+datestr+")";
						}
					}
					if(null!=status && status.getCode().equals("Waiting")){
						prams_.put("status_type",20);
					}else{
						prams_.put("status_type",21);
					}
					prams_.put("usserevent_time",his_.getResumeCoin());
				}
				prams_.put("usserevent",usserevent);
				result.add(prams_);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return result;
	}
	
	@Override
	public String getBuyContent(String buyhistoryid) throws Exception {
		BuyHistory his_ = moneydao.getBuyHistoryByid(buyhistoryid);
		String usserevent = "";
		if(null != his_){
			if(his_ instanceof ChannelBuyHistory){
				ChannelBuyHistory channeHistory = moneydao.getChannelBuyHistoryById(his_.getId());
				if(null!=channeHistory){
					usserevent =  channeHistory.getChannel().getTitle();
				}
			}else if(his_ instanceof OfflineEventsUserBuyHistory){
				OfflineEventsUserBuyHistory offBuyHistory = moneydao.getOfflineBuyHis(his_.getId());
				if(null!=offBuyHistory){
					String hql = " from " + OfflineEventsUser.class.getName() + " t left outer join fetch t.offlineEvents where t.id=:id";
					Map map = new HashMap();
					map.put("id", offBuyHistory.getOfflineEventsUser().getId());
					OfflineEventsUser offlineEventsUser = (OfflineEventsUser) moneydao.getICommonDaoService().getByHQLMap(hql, map);
					usserevent = offlineEventsUser.getOfflineEvents().getTitle();
				}
			}
			if(his_ instanceof VipBuyHistory){
				VipBuyHistory vip = (VipBuyHistory)his_;
				if(null!=vip.getValidEndTime()){
					String datestr = DateUtil.getInstance().dateToStringDate(vip.getValidEndTime());
					if(vip.getVipBuyRule() != null){
						Dictionary vipType = null;
						vipType = getVipTypeByBuyHistoryId(vip.getId());
						if(vipType != null){
							usserevent=vipType.getTitle()+"至("+datestr+")";
						}
						else{
							usserevent="购买会员至("+datestr+")";
						}
					}
					else{
						usserevent="购买会员至("+datestr+")";
					}
				}
			}
		}
		return usserevent;
	}
	/**
	 * 根据ruleId得到VipType
	 * @param ruleId
	 * @return
	 * @throws Exception 
	 */
	private Dictionary getVipTypeByRuleId(String ruleId) throws Exception{
		Dictionary result = null;
		String sql = "select t.vipType from "+VipBuyRule.class.getName()+" t where t.id = :id ";
		Map map = new HashMap();
		map.put("id", ruleId);
		List <Dictionary> list = this.moneydao.getICommonDaoService().queryList(sql,map);
		if(list != null && list.size() > 0){
			result = list.get(0);
		}
		return result;
	}
	/**
	 * 根据ruleId得到VipType
	 * @param vipId
	 * @return
	 * @throws Exception 
	 */
	private Dictionary getVipTypeByBuyHistoryId(String vhId) throws Exception{
		Dictionary result = null;
		String sql = "select t.vipBuyRule.vipType from  "+VipBuyHistory.class.getName()+
				" t where t.id = :id ";
		Map map = new HashMap();
		map.put("id", vhId);
		List <Dictionary> list = this.moneydao.getICommonDaoService().queryList(sql,map);
		if(list != null && list.size() > 0){
			result = list.get(0);
		}
		return result;
	}
	public void setBuyHistoryPayHistory(String buyid,String payid){
		try {
			moneydao.setBuyHistoryPayHistory(buyid, payid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	@Autowired
	@Qualifier("servicedictionary")
	IDictionary daoDictionary ;
	@Autowired
	@Qualifier("serviceusercoin")
	IUserCoinService serviceUserCoin;
	@Autowired
	@Qualifier("MoneyDao")
	IMoneyDao moneydao;
	public IMoneyDao getMoneydao() {
		return moneydao;
	}

	public void setMoneydao(IMoneyDao moneydao) {
		this.moneydao = moneydao;
	}


	public IVideoService getVideoService() {
		return videoService;
	}


	public void setVideoService(IVideoService videoService) {
		this.videoService = videoService;
	}


	public IDictionary getDaoDictionary() {
		return daoDictionary;
	}


	public void setDaoDictionary(IDictionary daoDictionary) {
		this.daoDictionary = daoDictionary;
	}


	public IUserCoinService getServiceUserCoin() {
		return serviceUserCoin;
	}


	public void setServiceUserCoin(IUserCoinService serviceUserCoin) {
		this.serviceUserCoin = serviceUserCoin;
	}
	@Override
	public User getUserByBuyHistoryId(String buyHistoryId) {
		try {
			BuyHistory buyhistory = moneydao.getBuyHistoryByid(buyHistoryId);
			return null==buyhistory?null:buyhistory.getUser();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	@Override
	public void setBuyHistoryError(String buyid) {
		try {
			// TODO Auto-generated method stub
			Dictionary paydic = daoDictionary.getDictionaryByDictionaryTypeCode("BuyStatus","Fail");
			moneydao.setBuyHistoryStatus(buyid, paydic);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
	}

	/**
	 * 获得有效的VIP购买规则
	 * 此处排除掉免费活动
	 * @return
	 */
	@Override
	public List<VipBuyRule> getValidVipBuyRule() {
		
		String sql = "select t from "+VipBuyRule.class.getName()+" t where t.vipType.code =:code and  t.valid = 1 order by t.orderCode asc ";
		Map<String,String> map = new HashMap<String, String>();
		map.put("code",chargeVipCode);
		List<VipBuyRule> vbrList = null;
		try {
			vbrList = this.getMoneydao().getICommonDaoService().queryList(sql,map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return vbrList;
	}
	/**
	 * 
	 * @return
	 */
	@Override
	public VipBuyRule getVipBuyRuleById(String id ) {
		VipBuyRule vbr = null;
		String sql = "select t from "+VipBuyRule.class.getName()+" t where t.id = :id order by t.orderCode asc ";
		Map map  = new HashMap();
		map.put("id", id);
		List<VipBuyRule> vbrList = this.getMoneydao().getICommonDaoService().getListBySQLMap(sql,map);
		if(vbrList != null && vbrList.size() > 0){
			vbr = vbrList.get(0);
		}
		return vbr;
	}
	@Override
	public PayHistory getpayHistory(String payid) {
		PayHistory payHistory=null;
		try {
			payHistory = moneydao.getPayHistoryByid(payid);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return payHistory;
	}
	@Override
	public PayHistory getpayHistory(String payid, String money) {
		PayHistory payHistory=null;
		try {
			String hql = " from " + PayHistory.class.getName() + " t left outer join fetch t.qrCodePic where t.id=:id and t.resumeCoin=:money";
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id",payid);
			map.put("money", Integer.parseInt(money.trim()));
			List<PayHistory> list = moneydao.getICommonDaoService().getListBySQLMap(hql, map);
			if(null != list && list.size() > 0){
				payHistory = list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return payHistory;
	}
	@Override
	public List<Dictionary> getDictionaries() {
		List<Dictionary> list=daoDictionary.getDictionaries("InvoiceType");
		return list;
	}
	@Override
	public Boolean editObject(PayHistory history) {
		try {
			moneydao.editObject(history);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	@Override
	public VipBuyRule getVipBuyRuleByHistoryid(String buyHistoryid) {
		// TODO Auto-generated method stub
		String hql=" from "+VipBuyHistory.class.getName() +" t left outer join fetch t.vipBuyRule where t.id=:id ";
		Map map  = new HashMap();
		map.put("id", buyHistoryid);
		List<VipBuyHistory> vips = null;
		try {
			vips = this.getMoneydao().getICommonDaoService().queryList(hql,map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(vips.size()>0){
			return vips.get(0).getVipBuyRule();
		}
		return null;
	}
	@Override
	public VipBuyHistory getVipByUserid(String userid) {
		String hql="from "+VipBuyHistory.class.getName()+" t left outer join fetch t.vipuser left outer join fetch t.status where t.vipuser.id=:id";
		Map map  = new HashMap();
		map.put("id", userid);
		List<VipBuyHistory> vip=this.getMoneydao().getICommonDaoService().getListByHQL(hql);
		if(vip.size()>0){
			return vip.get(0);
		}
		return null;
	}
	@Override
	public VipBuyHistory getVipBuyHistoryById(String id,String userId){
		String hql="from "+VipBuyHistory.class.getName()+" t left outer join fetch t.vipuser left outer join fetch t.vipBuyRule where t.vipuser.id=:userId and t.id=:vipBuyHisId";
		Map map  = new HashMap();
		map.put("userId", userId);
		map.put("vipBuyHisId", id);
		List<VipBuyHistory> vip=this.getMoneydao().getICommonDaoService().getListBySQLMap(hql, map);
		if(null != vip && vip.size() > 0){
			return vip.get(0);
		}
		return null;
	}

	

	
	
}
